package ar.com.larctest.forms;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;

import ar.com.larctest.R;
import ar.com.larctest.utils.AppGlobalVariables;
import ar.com.larctest.utils.Constants;
import ar.com.larctest.utils.CustomHttpClient;
import ar.com.larctest.utils.MCrypt;

public class LoginActivity extends Activity implements Runnable {
    private static final String TAG = "LoginActivity";
    private static final int iLoginIncorrect = 1;
    private static final int iLoginGrant = 0;

    Toast msgLogin;
    EditText etUserName, etPassword;
    Button butLogin;
    ProgressDialog dialog;

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etUserName = (EditText) findViewById(R.id.etUserName);
        etPassword = (EditText) findViewById(R.id.etPassword);
    }

    public void onClickLogin(View v) throws Exception
    {
        if(etUserName.getText().toString().equals("")) {
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

            TextView text = (TextView) layout.findViewById(R.id.text);
            text.setText(getText(R.string.Login_Msg_userRequired));

            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();
        }
        else if(etPassword.getText().toString().equals("")) {
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

            TextView text = (TextView) layout.findViewById(R.id.text);
            text.setText(getText(R.string.Login_Msg_passwordRequired));

            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();
        }
        else
        {
            dialog = ProgressDialog.show(LoginActivity.this, "", getString(R.string.Login_Msg_loadingMessagge), true);

            Thread thread = new Thread(this);
            thread.start();
        }
    }

    @Override
    public void run() {
        Looper.myLooper();
        Looper.prepare();

        try {
            MCrypt encryptAES = new MCrypt();
            String encryptPass = MCrypt.bytesToHex(encryptAES.encrypt(etPassword.getText().toString()));

            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("action", "validateUser"));
            postParameters.add(new BasicNameValuePair("userName", etUserName.getText().toString()));
            postParameters.add(new BasicNameValuePair("userPassword", encryptPass));

            String response = CustomHttpClient.executeHttpPost(Constants.URL, postParameters);
            JSONObject jsonUser = new JSONObject(response);

            if(jsonUser.getString("permission").equals("DENIED")) {
                Message msg = Message.obtain();
                msg.what = iLoginIncorrect;
                msg.obj = jsonUser.getString("permission");
                handler.sendMessage(msg);
            }
            else if(jsonUser.getString("permission").equals("GRANT"))
            {
                AppGlobalVariables.getInstance().setUserName(jsonUser.getString("userName"));
                AppGlobalVariables.getInstance().setUserCompleteName(jsonUser.getString("userCompleteName"));
                AppGlobalVariables.getInstance().setUserEMail(jsonUser.getString("userEMail"));
                AppGlobalVariables.getInstance().setIdUser(Integer.parseInt(jsonUser.getString("idUser")));

                Message msg = Message.obtain();
                msg.what = iLoginGrant;
                msg.obj = jsonUser.getString("permission");
                handler.sendMessage(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, e.getMessage());
            Message msg = Message.obtain();
            msg.what = iLoginIncorrect;
            msg.obj = e;
            handler.sendMessage(msg);
        }
    }

    private void updateActivity(Message msg)
    {
        if (msg.what == iLoginIncorrect) {
            msgLogin = Toast.makeText(this, getString(R.string.Login_Msg_incorrectLogin), Toast.LENGTH_LONG);
            msgLogin.setGravity(Gravity.CENTER,  msgLogin.getXOffset() / 2, msgLogin.getYOffset() / 2);
            msgLogin.show();
        }
        else {
            Intent intentMenu = new Intent(this, MenuActivity.class);
            startActivityForResult(intentMenu, 1);
        }
        dialog.dismiss();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            updateActivity(msg);
        }
    };
}
